<?php


namespace app\admin\validate;

use think\Validate;


/**
 * 商品验证器
 * Class Goods
 * @package app\Goods\validate
 * @author Mr.Liu
 * @create 2021-09-16 14:23
 */
class Policy extends Validate
{

    /**
     * 验证规则
     * @var string[]
     */
    protected $rule = [
        'sales_policy'                  => 'require|is_policy_unique:policy',
        'sales_policy_name'             => 'require|is_goods_unique:policy'

    ];

    /**
     * 错误信息
     * @var string[]
     */
    protected $message = [
        'sales_policy.require'                  => '销售政策编码必须填写',
        'sales_policy.is_policy_unique'          => '销售政策编码已存在',
        'sales_policy_name.is_goods_unique'          => '销售政策已存在',
        'sales_policy_name.require'              => '销售政策名称必须填写'

    ];


    /**
     * 场景
     * @var \string[][]
     */
    protected $scene = [
        'create'            => ['sales_policy','sales_policy_name'],
        'update'            => ['sales_policy','sales_policy_name'],
    ];


    /**
     * 验证name唯一性
     * @param $value
     * @param $rule
     * @param array $data
     * @param string $field
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author Mr.Liy
     * @create 2021-09-16 13:45
     */

    public function is_policy_unique($value, $rule, array $data = [], string $field = ''): bool
    {
        $id = $data['id'] ?? 0;
        $where = [
            ['delete_time','=',0],
            ['sales_policy','=',trim($value)],
        ];
        if($id){
            $where[] = ['id','<>',$id];
        }
        if(\app\admin\model\Policy::where($where)->value('id')){

            return false;
        }
        return true;

    }



    /**
     * 验证name唯一性
     * @param $value
     * @param $rule
     * @param array $data
     * @param string $field
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author Mr.Liy
     * @create 2021-09-16 13:45
     */

    public function is_goods_unique($value, $rule, array $data = [], string $field = ''): bool
    {


        $id = $data['id'] ?? 0;
        $where = [
            ['delete_time','=',0],
            ['sales_policy_name','=',trim($value)],
        ];
        if($id){
            $where[] = ['id','<>',$id];
        }
        if(\app\admin\model\Policy::where($where)->value('id')){

            return false;
        }
        return true;

    }


}
